<?php

namespace App\Admin\Actions\Grid\RowActions;

use App\Models\Project;
use App\Models\ProjectAgreement;
use App\Models\ProjectUser;
use App\Models\User;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;

class DeleteUserAction extends RowAction
{
    protected $title = '   <i class="feather icon-alert-triangle text-danger"></i> <span class="text-danger">删除</span> &emsp;';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $id = $request->input('id');
        $projectUserModel = ProjectUser::where('user_id', $id)->get();

        $projectName = Project::whereIn('id', $projectUserModel->pluck('project_id'))->pluck('project_name');

        if (!empty($projectName->toArray())) {
            $name = '';
            foreach ($projectName as $key => $val) {
                $name .= '《' . $val . '》';
            }
            return $this->response()->alert()->error('这名医生正在参与' . $name . '如果需要删除，请先删除这名医生参与的项目！');
        }

        $res = User::where('id', $id)->delete();
        if ($res) {
            return $this->response()->success('删除成功')->refresh();
        } else {
            return $this->response()->error('删除失败')->refresh();
        }
    }


    public function confirm()
    {
        $user = User::find($this->row()->id);
        $projectUserModel = ProjectUser::where('user_id', $this->row()->id)->get();
        $projectName = Project::whereIn('id', $projectUserModel->pluck('project_id'))->pluck('project_name');
        // $projectName->push('测试多个名称');

        if (!empty($projectName->toArray())) {
            $name = '';
            foreach ($projectName as $key => $val) {
                $name .= '《' . $val . '》';
            }
            return ['这名医生正在参与' . $name . '如果需要删除，请先删除这名医生参与的项目！'];
        } else {
            return ['您确定要删除 <' . $user->realname . ' >这名医生吗？'];
        }
    }

    /**
     * 设置要POST到接口的数据
     *
     * @return array
     */
    public function parameters()
    {
        return [
            // 发送当前行 username 字段数据到接口
            'id' => $this->row->id,
        ];
    }
}
